#include "common.h"
#include "../../config/config.h"


int db_common_mysql_connect(MYSQL **conn)
{
    if (conn == NULL) {
        return SYSTEM_ERR_INVALID_ARGUMENT;
    }

    // 初始化 MySQL 连接对象
    pthread_mutex_lock(&g_mysql_lock);
    MYSQL *mysql_conn = mysql_init(NULL);
    if (mysql_conn == NULL) {
        pthread_mutex_unlock(&g_mysql_lock);
        return SYSTEM_ERR_DB_INIT;
    }

    // 使用全局配置建立连接
    const char *host = g_mysql_host;
    int port = g_mysql_port;
    const char *user = g_mysql_user;
    const char *password = g_mysql_password;
    const char *db = g_mysql_db;

    if (mysql_real_connect(mysql_conn, host, user, password, db, port, NULL, 0) == NULL) {
        mysql_close(mysql_conn);
        pthread_mutex_unlock(&g_mysql_lock);
        return SYSTEM_ERR_DB_CONNECT;
    }
    pthread_mutex_unlock(&g_mysql_lock);

    *conn = mysql_conn;
    return SYSTEM_ERR_OK; // 成功
}